/*
LevelAction.cpp
描述游戏事件
*/

#include <LevelAction.h>
#include <iostream>
#include <vector>
#include <string>
#include <json/json.h>

using namespace std;

string LevelAction::serializeAction() {
    Json::Value root;
    root["a"] = actionName;
    Json::Value paramsArray(Json::arrayValue);
    for (const auto& param : paramsList) {
        paramsArray.append(param);
    }
    root["p"] = paramsArray;
    root["ts"] = timeStamp;
    // 填充对象的参数
    Json::FastWriter fastWriter;
    string result = fastWriter.write(root);
    return result;
    // 返回序列化后的对象
}

void LevelAction::deserializeAction(const string& jsonContent) {
    try {
        Json::Value root;
        Json::CharReaderBuilder builder;
        unique_ptr<Json::CharReader> charReader(builder.newCharReader());
        charReader->parse(&jsonContent[0], &jsonContent[0] + jsonContent.size(), &root, nullptr);
        actionName = root["a"].asString();
        for (const auto& param : root["p"]) {
            paramsList.push_back(param.asString());
        }
        timeStamp = root["ts"].asInt64();
    }
    catch (exception e) {
        printf("Error occured when deserializing : %s\nThis json message was ignored.\n", jsonContent.c_str());
    }
}
